//
//  CZTabBarController.swift
//  weibo27
//
//  Created by mac on 16/4/16.
//  Copyright © 2016年 it.cast. All rights reserved.
//

import UIKit

class CZTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

       //在添加控制器的时候，tabBar是没有被创建出来的
        addChildViewControllers()
        
//        print(tabBar.subviews)
        
        setupComposedButton()
        
        

    }

    override func viewWillAppear(animated: Bool) {
        // 会创建 tabBar 中的所有控制器对应的按钮！
        super.viewWillAppear(animated)
        
        // 将撰写按钮弄到最前面
        tabBar.bringSubviewToFront(composedButton)

    }
    
    //懒加载一个控件 使用便利构造函数快速创建撰写按钮
    private lazy var composedButton: UIButton = UIButton (
        imageName: "tabbar_compose_icon_add",
        backGroudImage: "tabbar_compose_button")
   
    //点击撰写按钮出发的事情 方法私有化以后，就必须使用@objc说明，不然就会报错
    @objc private func clickComposedButton(){
        
//        print("撰写按钮被点击了")
        
        let vc:UIViewController
        
        if CZUserAccountViewModel.shareModel.userLogin{
            vc = CZComposeController()
        }else{
            vc = CZOAuthView()
        }
        
        let nav = UINavigationController(rootViewController: vc)
        
        //点击之后跳转页面
        presentViewController(nav, animated: true, completion: nil)
    }
    
    

}

extension CZTabBarController{
    
    //添加撰写按钮
    private func setupComposedButton(){
        
        tabBar.addSubview(composedButton)
        
        let w = kScreenW / CGFloat(childViewControllers.count)
        
        composedButton.frame = CGRectInset(tabBar.bounds, w*2, 0)
        
        //给按钮添加一个点击事件
        composedButton.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
   private func addChildViewControllers(){
        
        addChildViewController(CZHomeController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(CZMessageController(), title: "消息", imageName: "tabbar_message_center")
        
        //就是一个对多态的简单实用，添加一个控件
        addChildViewController(UIViewController())
        
        addChildViewController(CZDiscoverController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(CZProfileController(), title: "我", imageName: "tabbar_profile")
        
    }
    
   private func addChildViewController(vc: UIViewController, title:String, imageName:String) {
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
    
}







